package com.example.controller;

import com.example.entity.LoginRequest;
import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class LoginController {

    @Resource
    private UserService userService;

    @GetMapping
    public String loginPage(HttpSession session) {
        Object user = session.getAttribute("user");
        if (user != null)
            session.removeAttribute("user");
        return "login";
    }

    @PostMapping("/login")
    public String login(LoginRequest loginRequest,
                        HttpSession session,
                        RedirectAttributes attributes) {
        User user = userService.checkUser(loginRequest.getUsername(), loginRequest.getPassword());
        System.out.println(loginRequest);
        System.out.println(user);
        if (user == null) {
            return "redirect:/user";
        }
        session.setAttribute("user",user);

        return "index";
    }

    @GetMapping("/logout")
    public String logout(Model model, HttpSession session) {
        session.removeAttribute("user");
        model.addAttribute("quit","安全退出！");
        return "redirect:/user";
    }
}
